<script setup>
import {computed, onMounted, ref} from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useStore } from 'vuex';
import api from "@/api/index.js";
import cache from "@/utils/cacheGetter.js";
import {useRouter} from "vue-router";
import {CloseBold} from "@element-plus/icons-vue";

const store = useStore()
const router = useRouter()
const dialogVisible = ref(false);
const userProfile = computed(()=>store.getters?.currentUser)
const activeTab = ref('basic')
const userProfileForm = ref({
  username: userProfile.value.username,
  email: userProfile.value.email,
  phone: userProfile.value.phone,
  avatar: userProfile.value.avatar
});
const alterPasswordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const handleAlterPassword = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '更新中...'
  });
  api.post('user/alterPassword',alterPasswordForm.value).then(resp=>{
    ElMessage(resp.data)
    loading.close()
    handlerClosePassword()
  }).catch(e=>{
    ElMessage.error(e.response.data)
    loading.close()
  })
  alterPasswordForm.value.oldPassword=alterPasswordForm.value.newPassword=alterPasswordForm.value.confirmPassword=''
}
// userProfile
const history = ref([])
const historyPage = ref({
  page: 1,
  pageSize: 10,
  total: 0
})
const fetchHistory = () => {
  api.getPageNoQuery('userLearningHistory/user/page',{
    page: historyPage.value.page,
    pageSize: historyPage.value.pageSize
  }).then(resp=>{
    history.value = resp.data.data
    historyPage.value.total = resp.data.total
  })
}
const onHistoryCurrentChange = (current) => {
  historyPage.value.page = current
  fetchHistory()
}
const onHistorySizeChange = (size) => {
  historyPage.value.pageSize = size
  fetchHistory()
}
const deleteCurrent = (id)=>{
  api.delete(`/userLearningHistory/user/delete/${id}`).then(()=>{
    ElMessage.success('删除成功')
    fetchHistory()
  })
}
const handlerClosePassword = (id)=>{
  dialogVisible.value = false;
  alterPasswordForm.value.oldPassword=alterPasswordForm.value.newPassword=alterPasswordForm.value.confirmPassword=''
}
const collection=ref([])
const collectionPage = ref({
  page: 1,
  pageSize: 10,
  total: 0
})
const fetchCollection = ()=>{
  api.get(`/userCollection/user/page`,{
    page:collectionPage.value.page,
    pageSize:collectionPage.value.pageSize
  }).then(resp=>{
    collection.value = resp.data.data
    collectionPage.value.total = resp.data
  })
 }
const onCollectionCurrentChange = (current) => {
  historyPage.value.page = current
  fetchCollection()
}
const onCollectionSizeChange = (size) => {
  historyPage.value.pageSize = size
  fetchCollection()
}
const deleteCurrentCollection = (id)=>{
  api.delete(`/userCollection/user/delete/${id}`).then(()=>{
    ElMessage.success('删除成功')
    fetchCollection()
  })
}

const userInfo = ref({
  learningMins: 1,
  courseProgress: '75%',
  recommendTags: ['前端开发', 'vue','ts'],
  history: [
    { id: 1,img:'/vue3.png', title: 'Vue3 核心原理', time: '2023-08-15', progress: 65 },
    { id: 2,img:'/ts.png', title: 'TypeScript 进阶', time: '2023-08-14', progress: 80 }
  ]
});
const handleEdit = () => {
  dialogVisible.value = true;
};

const handleSubmit = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '更新中...'
  });
  api.put('user/updateProfile', userProfileForm.value).then(resp => {
    store.commit('SET_USER',resp.data)
    loading.close();
    ElMessage.success('更新成功！');
  }).catch(e=>{
    ElMessage.error('更新失败')
    loading.close();
  })
};

const baseURL = api.getInstance().defaults.baseURL
const handleAvatarSuccess = (resp, file) => {
  userProfileForm.value.avatar = resp.url
};

const learnedMins = ref(0)
const fetchLearnTime = () => {
  api.get('/userLearningHistory/user/sum').then(resp=>{
    learnedMins.value = resp.data/60
  })
};

onMounted(()=>{
  fetchCollection()
  fetchHistory()
  fetchLearnTime()
})
</script>

<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div style="padding-top: 50px">
        <el-avatar :size="80" :src="userProfile?.avatar? baseURL+'user/download/'+userProfile.avatar:'/vite.svg'" class="user-avatar" />
        <h1>{{ userProfile?.username }}的个人中心</h1>
      </div>
      <div class="user-header">

        <div class="user-info">

          <div class="contact-info">
            <span><el-icon><Message /></el-icon> {{ userProfile?.email }}</span>
            <span><el-icon><Iphone /></el-icon> {{ userProfile?.phone }}</span>
          </div>
        </div>
        <el-button style="margin-right:50px" type="primary" @click="handleEdit">编辑资料</el-button>
      </div>

      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-statistic title="累计学习时长" :value="learnedMins" suffix="分钟" />
          </el-col>
          <el-col :span="8">

          </el-col>
        </el-row>
      </div>

      <!-- 浏览历史卡片 -->
      <el-card class="history-card">
        <template #header>
          <div class="card-header">
            <span>最近学习记录</span>
          </div>
        </template>
        
        <el-timeline>
          <el-pagination
              :current-page="historyPage.current"
              :page-size="historyPage.size"
              :page-sizes="[5, 10, 15, 20]"
              :total="historyPage.total"
              class="pagination"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="onHistorySizeChange"
              @current-change="onHistoryCurrentChange"
          />
          <el-timeline-item
            v-for="item in history"
            :key="item.historyId"
            :timestamp="item.accessedAt"
            placement="top"
          >
            <el-card>
              <el-row>
                <el-button style="margin-right: 30px" circle type="danger" @click="deleteCurrent(item.historyId)"><el-icon><CloseBold/></el-icon></el-button>
                <el-image 
                  style="
                    display: inline-block;
                    height: 50px;
                    border-radius: 4px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    margin-right: 15px;
                  " 
                  :src="baseURL+'resource/download/'+cache.get('resource',item.resourceId)?.imgPath"
                  fit="cover"
                ></el-image>
                <div class="course-info">
                  <el-link @click="router.push('/detail/'+item.resourceId)" style="margin: 0 0 5px; font-size: 16px; color: #303133">{{ cache.get('resource',item.resourceId)?.title }}</el-link>
                  <span style="margin-left: 50px">(阅读了{{item.studyDuration}}秒)</span>
                </div>
              </el-row>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </el-card>

    <el-card style="margin-top:50px">
      <template #header>
        <div class="card-header">
          <span>我的收藏</span>
        </div>
        <el-pagination
            :current-page="collectionPage.current"
            :page-size="collectionPage.size"
            :page-sizes="[5, 10, 15, 20]"
            :total="collectionPage.total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="onCollectionSizeChange"
            @current-change="onCollectionCurrentChange"
        />
        <el-timeline>
        <el-timeline-item
            v-for="item in collection"
            :timestamp="item.collectedAt"
            placement="top"
        >
          <el-card>
            <el-row>
              <el-button style="margin-right: 30px" circle type="danger" @click="deleteCurrentCollection(item.resourceId)"><el-icon><CloseBold/></el-icon></el-button>
              <el-image
                  style="
                    display: inline-block;
                    height: 50px;
                    border-radius: 4px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    margin-right: 15px;
                  "
                  :src="baseURL+'resource/download/'+cache.get('resource',item.resourceId)?.imgPath"
                  fit="cover"
              ></el-image>
              <div class="course-info">
                <el-link @click="router.push('/detail/'+item.resourceId)" style="margin: 0 0 5px; font-size: 16px; color: #303133">{{ cache.get('resource',item.resourceId)?.title }}</el-link>
              </div>
            </el-row>
          </el-card>
        </el-timeline-item>
        </el-timeline>
      </template>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="编辑资料"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      append-to-body
      transition="el-fade-in-linear"
    >
      <el-tabs v-model="activeTab" class="edit-tabs">
        <el-tab-pane label="基本信息" name="basic">
          <el-form label-width="100px">
            <el-form-item label="头像">
              <el-upload
                  :action="baseURL+'user/upload'"
                  :show-file-list="false"
                  :auto-upload="true"
                  @success="handleAvatarSuccess"
              >
                <el-avatar :size="80" :src="userProfileForm?.avatar? baseURL+'user/download/'+userProfileForm.avatar:'/vite.svg'" />
                <template #tip>
                  <div class="el-upload__tip">点击头像更换</div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input disabled v-model="userProfileForm.username" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userProfileForm.email" />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="userProfileForm.phone" />
            </el-form-item>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认修改</el-button>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="alterPwd">
          <el-form label-width="100px">
            <el-form-item label="原密码">
              <el-input type="password" show-password v-model="alterPasswordForm.oldPassword" />
            </el-form-item>
            <el-form-item label="新密码">
              <el-input type="password" show-password v-model="alterPasswordForm.newPassword" />
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input type="password" show-password v-model="alterPasswordForm.confirmPassword" />
            </el-form-item>

            <el-button @click="handlerClosePassword">取消</el-button>
            <el-button v-if="alterPasswordForm.newPassword===alterPasswordForm.confirmPassword" type="primary" @click="handleAlterPassword">修改密码</el-button>
            <h3 v-else style="color:red;">两次密码不一致</h3>

          </el-form>
        </el-tab-pane>
      </el-tabs>
      

    </el-dialog>
  </div>
</template>

<style scoped>
.profile-container {
  padding:50px 300px;
  background-color: #f7faf6;
  min-height: 100vh;
}

.profile-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.user-header {
  display: flex;
  align-items: center;
  gap: 30px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-info {
  flex-grow: 1;
}

.contact-info {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  margin-left: 50px;
  color: #666;
}

.stats-section {
  padding: 20px;
}

.tags-box {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.mr-10 {
  margin-right: 10px;
  margin-bottom: 10px;
}

.history-card {
  margin-top: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.el-timeline {
  padding-left: 10px;
}

.el-upload__tip {
  margin-top: 10px;
  color: #999;
}

/* 弹窗进入动画 */
.el-fade-in-linear-enter-active {
  transition: all 0.3s ease-out;
}

.el-fade-in-linear-enter-from {
  opacity: 0;
  transform: translateY(-20px);
}
</style>